package com.zhao.dome01.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Map;

//TODO  jwt令牌自动续期的问题还没有实现  之后要进行jwt令牌自动续期的代码书写
public class JwtUtil {
    //定义令牌默认有效期
    private final static Long defaultExpire = 1000 * 60 * 60 * 7L;
    private final static String SECRET = "ABCDEFGHIGKLMNOPQRSTUVWXYZ.ABCDEFGHIGKLMNOPQRSTUVWXYZ.ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    private static final SecretKey token_key = Jwts.SIG.HS256.key()
            .random(new SecureRandom(SECRET.getBytes(StandardCharsets.UTF_8)))
            .build();


    public static String createToken(Map<String, Object> claims) {
        return createToken(claims, defaultExpire);

    }

    /**
     * 生成token
     */
    public static String createToken(Map<String, Object> claims, long expire) {
        Date now = new Date();

        JwtBuilder jwtBuilder = Jwts.builder()
                .claims(claims)
                .issuedAt(now)//签发时间
                .expiration(new Date(now.getTime() + expire))//过期时间
                .signWith(token_key);

        return jwtBuilder.compact();
    }

    /**
     * 解析tokens
     *
     */
    public static Claims getClaims(String token) {
        try {
            return Jwts
                    .parser()
                    .verifyWith(token_key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (SignatureException exception) {
            throw new RuntimeException("token签名异常");
        } catch (ExpiredJwtException exception) {
            throw new RuntimeException("token签名已过期");
        } catch (MalformedJwtException exception) {
            throw new RuntimeException("token格式异常");
        } catch (UnsupportedJwtException exception) {
            throw new RuntimeException("该token不知处解析");
        } catch (IllegalArgumentException exception) {
            throw new RuntimeException("非法请求");
        } catch (Exception exception) {
            throw new RuntimeException("未知异常");
        }
    }
}
